package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.dao.CustomerDao;
import com.cdvtc.flower.dao.impl.CustomerDaoImpl;
import com.cdvtc.flower.model.Customer;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;


@WebServlet(name = "registerServlet", urlPatterns = "/registerServlet")
public class registerServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取参数前设置编码，可解决post方式提交的中文乱码
        request.setCharacterEncoding("UTF8");

        //获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        System.out.println(username);
        System.out.println(phone);
        System.out.println(password);
        System.out.println(email);
        System.out.println(address);
        /**
         * 数据验证
         */
        CustomerDao customerDao = new CustomerDaoImpl();

        String error_phone = null;
        if(customerDao.isUserExisted("phone", phone)){
            error_phone = "手机号码已经存在！";
            request.setAttribute("page", "register.jsp");
            request.setAttribute("message", error_phone);
            request.getRequestDispatcher("alert_jump.jsp").forward(request, response);;
        }
        String error_email = null;
        if(email != null && customerDao.isUserExisted("email", email)){ // 注意：email为null时不验证
            error_email = "电子邮件已经存在！";
            request.setAttribute("page", "register.jsp");
            request.setAttribute("message", error_email);
            request.getRequestDispatcher("alert_jump.jsp").forward(request, response);;
        }

        /**
         * 根据验证结果进行页面跳转
         */
        if(error_phone==null && error_email==null){ //验证通过
            Customer customers = new Customer();
            customers.setUser_name(username);
            customers.setEmail(email);
            customers.setAddress(address);
            customers.setPassword(password);
            customers.setPhone(phone);
            System.out.println(customers);

            customerDao.addCustomer(customers);

            //进入登陆页面
//        response.sendRedirect("login.jsp");
            request.setAttribute("page", "login.jsp");
            request.setAttribute("message", "账户注册成功，请使用该账户登陆系统。");
            request.getRequestDispatcher("alert_jump.jsp").forward(request, response);
        } else { //返回至注册页面
            request.setAttribute("message", "账户注册失败！");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}

